<template>
  <div>
    <el-form class="detail-form-content" ref="ruleForm" :model="ruleForm" label-width="auto">
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="flag == 'leadership'" label='领导名称' prop="lingdaoName">
            <el-input v-model="ruleForm.leadershipNick" placeholder='领导名称' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="flag == 'leadership'" label='领导手机号' prop="lingdaoPhone">
            <el-input v-model="ruleForm.leadershipPhone" placeholder='领导手机号' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="flag == 'leadership'" label='领导身份证号' prop="lingdaoIdNumber">
            <el-input v-model="ruleForm.leadershipNumber" placeholder='领导身份证号' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="flag == 'leadership'" label='领导头像' prop="lingdaoPhoto">
            <!-- <file-upload tip="点击上传照片" action="file/upload" :limit="1" :multiple="true"
              :fileUrls="ruleForm.leadershipImgUrl ? $base.imgUrl + ruleForm.leadershipImgUrl : ''"
              @change="lingdaoPhotoUploadChange"></file-upload> -->
            <!-- <el-image style="width: 148px; height: 148px" :src="$base.imgUrl + ruleForm.leadershipImgUrl"
              fit="fit"></el-image> -->
            <el-upload list-type="picture-card" class="upload-demo" action="#" :on-change="handleChange"
              :before-remove="beforeRemove" :limit="1" accept=".jpg, .png, .jpeg" :on-exceed="handleExceed"
              :on-progress="handleProgress" :auto-upload="false" :file-list="fileList">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过10MB</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="flag == 'leadership'" label='领导邮箱' prop="lingdaoEmail">
            <el-input v-model="ruleForm.leadershipEmail" placeholder='领导邮箱' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="flag == 'user'" label='职员名称' prop="userNick">
            <el-input v-model="ruleForm.userNick" placeholder='职员名称' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="flag == 'user'" label='职员手机号' prop="userPhone">
            <el-input v-model="ruleForm.userPhone" placeholder='职员手机号' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="flag == 'user'" label='职员身份证号' prop="userId">
            <el-input v-model="ruleForm.userId" placeholder='职员身份证号' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="flag == 'user'" label='职员头像' prop="userImgUrl">
            <!-- <el-image style="width: 148px; height: 148px" :src="$base.imgUrl + ruleForm.userImgUrl"
              fit="fit"></el-image> -->
            <el-upload list-type="picture-card" class="upload-demo" action="#" :on-change="handleChange"
              :before-remove="beforeRemove" :limit="1" accept=".jpg, .png, .jpeg" :on-exceed="handleExceed"
              :on-progress="handleProgress" :auto-upload="false" :file-list="fileList">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过10MB</div>
            </el-upload>
            <!-- <file-upload tip="点击上传照片" action="#" :limit="1" :multiple="true"
              @change="userPhotoUploadChange"></file-upload> -->
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item v-if="flag == 'user'" label='科室' prop="userDivisionName">
            <!-- divisionChangeForm.divisionName -->
            <el-select v-model="divisionChangeForm.divisionName" placeholder='请选择科室' @change="divisionChange"
              value-key="divisionId">
              <el-option v-for="(item, index) in keshiTypesOptions" v-bind:key="item.divisionId"
                :label="item.divisionName" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="flag == 'user'" label='职员邮箱' prop="userEmail">
            <el-input v-model="ruleForm.userEmail" placeholder='职员邮箱' clearable></el-input>
          </el-form-item>
        </el-col>

        <el-form-item v-if="flag == 'admin'" label="用户名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="用户名" @input="input"></el-input>
        </el-form-item>
        <el-col :span="12">
          <el-form-item v-if="flag != 'users' && (flag == 'user'
            || flag == 'leadership')" label="性别" prop="userSex">
            <el-select v-model="sexChangeForm.name" placeholder="请选择性别" @change="sexChange" value-key="id">
              <el-option v-for="(item, index) in sexTypesOptions" v-bind:key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="onUpdateHandler">修 改</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
// 数字，邮件，手机，url，身份证校验
import { isNumber, isIntNumer, isEmail, isMobile, isPhone, isURL, checkIdCard } from "@/utils/validate";

export default {
  data() {
    return {
      ruleForm: {
        name: ''
      },
      flag: '',
      usersFlag: false,
      fileList: [],
      // sexTypesOptions : [],
      // 注册表 科室职员
      // 注册的类型字段 科室职员
      // 性别
      sexTypesOptions: [],
      // 科室
      keshiTypesOptions: [],
      // 注册表 领导
      // 注册的类型字段 领导
      // 性别
      sexTypesOptions: [
        {
          id: 0,
          name: '男'
        },
        {
          id: 1,
          name: '女'
        },
        {
          id: 2,
          name: '未知'
        }
      ],
      sexChangeForm: {
        name: ''
      },
      divisionChangeForm: {
        divisionName: ''
      }
    };
  },
  mounted() {
    //获取当前登录用户的信息
    var table = this.$storage.get("sessionTable");
    this.sessionTable = this.$storage.get("sessionTable");
    this.role = this.$storage.get("role");
    if (this.role != "管理员") {
    }

    this.flag = table;
    this.$http({
      url: `${this.$storage.get("sessionTable")}/${this.$storage.get("sessionTable")}/get_${this.$storage.get("sessionTable")}`,
      method: "get"
    }).then(({ data }) => {
      if (data && data.code === 200) {
        console.log('个人信息', data);
        this.ruleForm = data.data
        this.divisionChangeForm.divisionName = data.data.userDivisionName
        if (this.$storage.get("sessionTable") == "user") {
          this.sexChangeForm.name = data.data.userSex == null ? '' : (data.data.userSex == 0 ? '男' : (data.data.userSex == 1 ? '女' : '未知'))
          this.fileList.push({
            url: this.$base.imgUrl + data.data.userImgUrl,
            name: data.data.userImgUrl,
            file: new File([], data.data.userImgUrl, {})
          })
        } else if (this.$storage.get("sessionTable") == "leadership") {
          this.sexChangeForm.name = data.data.leadershipSex == null ? '' : (data.data.leadershipSex == 0 ? '男' : (data.data.leadershipSex == 1 ? '女' : '未知'))
          this.fileList.push({
            url: this.$base.imgUrl + data.data.leadershipImgUrl,
            name: data.data.leadershipImgUrl,
            file: new File([], data.data.leadershipImgUrl, {})
          })
        } else {
          this.ruleForm.name = data.data.adminName
        }

        // this.
        // 注册表 科室职员
        // 注册表 领导
      } else {
        this.$message.error(data.message);
      }
    });

    // 注册表 科室职员 的级联表
    // 注册表 领导 的级联表

    // this.$http({
    //   url: `dictionary/page?page=1&limit=100&sort=&order=&dicCode=sex_types`,
    //   method: "get"
    // }).then(({ data }) => {
    //   if (data && data.code === 0) {
    //     this.sexTypesOptions = data.data.list;
    //   } else {
    //     this.$message.error(data.message);
    //   }
    // });

    this.$http({
      url: `list/api/division_api`,
      method: "get"
    }).then(({ data }) => {
      console.log('科室', data);
      if (data && data.code === 200) {
        this.keshiTypesOptions = data.data;
      } else {
        this.$message.error(data.message);
      }
    });
  },
  methods: {
    input() {
      this.$forceUpdate()
    },
    chongzhi() {
      this.$router.replace({ path: "/pay" });
    },
    sexChange(e) {
      this.ruleForm.userSex = e.id
      this.ruleForm.userSexName = e.name
      this.ruleForm.leadershipSex = e.id
      console.log(this.ruleForm)
    },
    divisionChange(e) {
      this.ruleForm.userDivisionId = e.divisionId
      this.divisionChangeForm.divisionName = e.divisionName
    },
    tixian() {
      let _this = this;
      this.$confirm(`确定要提现么?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        _this.ruleForm.newMoney = 0;
        _this.$http({
          url: `${this.$storage.get("sessionTable")}/update`,
          method: "post",
          data: this.ruleForm
        }).then(({ data }) => {
          if (data && data.code === 0) {
            _this.$message({ message: "提现成功", type: "success", duration: 1500, onClose: () => { } });
          } else { this.$message.error(data.message); }
        });
      });
    },
    lingdaoPhotoUploadChange(fileUrls) {
      this.ruleForm.userImgUrl = fileUrls;
    },
    userPhotoUploadChange(fileUrls) {
      console.log(fileUrls);
      this.ruleForm.userImgUrl = fileUrls
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleProgress(event, file, fileList) {
      console.log('event', event);
      console.log('file', file);
      console.log('fileList', fileList);
      console.log('handleProgress');
      this.ruleForm.userImgUrl = file.name
      this.ruleForm.leadershipImgUrl = file.name
      this.ruleForm.file = file.name
    },
    handleChange(file, fileList) {
      const imgFormat = file.raw.type === "image/jpeg" || file.raw.type === "image/png" || file.raw.type === "image/jpg"
      const isLt10M = file.raw.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.warning("上传图片大小不能超过 10M!")
        this.fileList = []
        return false
      } else if (!imgFormat) {
        this.$message.warning("上传图片格式只能是jpg、jpeg、png!")
        this.fileList = []
        return false
      } else {
        console.log(file);
        console.log(fileList);
        this.fileList = fileList
        this.ruleForm.userImgUrl = file.name
        this.ruleForm.leadershipImgUrl = file.name
        this.ruleForm.file = file.name
      }
    },

    onUpdateHandler() {
      if ((!this.ruleForm.leadershipNick) && 'leadership' == this.flag) {
        this.$message.error('领导名称不能为空');
        return
      }

      if ('leadership' == this.flag && this.ruleForm.leadershipPhone && (!isMobile(this.ruleForm.leadershipPhone))) {
        this.$message.error(`手机应输入手机格式`);
        return
      }
      if ((!this.ruleForm.leadershipNumber) && 'leadership' == this.flag) {
        this.$message.error('领导身份证号不能为空');
        return
      }

      if ((!this.ruleForm.leadershipImgUrl) && 'leadership' == this.flag) {
        this.$message.error('领导头像不能为空');
        return
      }

      if ('leadership' == this.flag && this.ruleForm.leadershipEmail && (!isEmail(this.ruleForm.leadershipEmail))) {
        this.$message.error(`邮箱应输入邮箱格式`);
        return
      }
      if ((!this.ruleForm.userNick) && 'user' == this.flag) {
        this.$message.error('职员名称不能为空');
        return
      }

      if ('user' == this.flag && this.ruleForm.userPhone && (!isMobile(this.ruleForm.userPhone))) {
        this.$message.error(`手机应输入手机格式`);
        return
      }
      if ((!this.ruleForm.userId) && 'user' == this.flag) {
        this.$message.error('职员身份证号不能为空');
        return
      }

      if ((!this.ruleForm.userImgUrl) && 'user' == this.flag) {
        this.$message.error('职员头像不能为空');
        return
      }

      if ((!this.divisionChangeForm.divisionName) && 'user' == this.flag) {
        this.$message.error('科室不能为空');
        return
      }

      if ('user' == this.flag && this.ruleForm.userEmail && (!isEmail(this.ruleForm.userEmail))) {
        this.$message.error(`邮箱应输入邮箱格式`);
        return
      }
      if ((!this.sexChangeForm.name) && (this.flag == 'user'
        || this.flag == 'leadership')) {
        this.$message.error('性别不能为空');
        return
      }
      if ('users' == this.flag && this.ruleForm.username.trim().length < 1) {
        this.$message.error(`用户名不能为空`);
        return
      }
      if ('admin' == this.flag && this.ruleForm.name.trim().length < 1) {
        this.$message.error(`用户名不能为空`);
        return
      }

      if (this.$storage.get("sessionTable") == "user") {
        const param = new FormData()
        const obj = {}
        this.fileList.forEach((val, index) => {
          obj.file = param.append('file', val.raw)
        })
        obj.divisionId = param.append('divisionId', this.ruleForm.userDivisionId)
        obj.sex = param.append('sex', this.ruleForm.userSex)
        this.$http({
          url: `${this.$storage.get("sessionTable")}/${this.$storage.get("sessionTable")}/update_${this.$storage.get("sessionTable")}_detail`,
          method: "post",
          data: param
        }).then(({ data }) => {
          if (data && data.code === 200) {
            this.$message({
              message: "修改信息成功",
              type: "success",
              duration: 1500,
              onClose: () => {
              }
            });
          } else {
            this.$message.error(data.message);
          }
        });
      } else if (this.$storage.get("sessionTable") == "leadership") {
        const param = new FormData()
        const obj = {}
        this.fileList.forEach((val, index) => {
          obj.file = param.append('file', val.raw)
        })
        obj.sex = param.append('sex', this.ruleForm.leadershipSex)
        this.$http({
          url: `${this.$storage.get("sessionTable")}/${this.$storage.get("sessionTable")}/update_${this.$storage.get("sessionTable")}_detail`,
          method: "post",
          data: param
        }).then(({ data }) => {
          if (data && data.code === 200) {
            this.$message({
              message: "修改信息成功",
              type: "success",
              duration: 1500,
              onClose: () => {
              }
            });
          } else {
            this.$message.error(data.message);
          }
        });
      } else {
        this.$http({
          url: `${this.$storage.get("sessionTable")}/${this.$storage.get("sessionTable")}/update_admin_message?name=${this.ruleForm.name}`,
          method: "get"
        }).then(({ data }) => {
          if (data && data.code === 200) {
            this.$message({
              message: "修改信息成功",
              type: "success",
              duration: 1500,
              onClose: () => {
              }
            });
          } else {
            this.$message.error(data.message);
          }
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
